package woaini.wind.bot.command.qylc.app.ticket.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONPath;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import woaini.wind.bot.core.exception.BotAssertTool;
import woaini.wind.bot.core.exception.enums.BotExceptionType;

/**
 * 中台的api
 *
 * @see woaini.wind.bot.command.qylc.app.ticket.api.CenterApi
 * @author yefeng {@date 2025-06-16 11:59:47}
 */
@UtilityClass
@Slf4j
public class CenterApi {

  public static final String SERVICE_URL = "http://service.mall.hgscn.com";

  public static final String username = "admin";
  public static final String password = "hgs.2024!@#";

  public static String TOKEN = null;

  public String login() {

    String url = SERVICE_URL + "/api/login/account";

    String reqBody =
        STR."""
    {
        "username": "\{username}",
        "password": "\{password}",
        "captchaVerification": "JvVJJAHY1j7RvowLq5CftwcWFJwiJRCTq"
    }
    """;

    String response = HttpRequest.post(url).body(reqBody).execute().body();
    TOKEN = (String) JSONPath.eval(response, "$.data.jwt");
    return TOKEN;
  }

  public String searchResourcesOrderInfo(String cardNo){
    String url = SERVICE_URL + "/api/platform/order/resources/list?orderStatusList=FINISH_PAY,RECEIPT,FINISH," +
      STR."FINISH_ING&tou/istSearch=\{cardNo}&pageNumber=1&pageSize=15";
    HttpRequest httpRequest = HttpRequest.get(url);
    return commonPost(httpRequest,false);
  }

  public String searchPacketOrderInfo(String cardNo){
    String url = SERVICE_URL + STR."/api/platform/order/resources/list?touristSearch=\{cardNo}&pageNumber=1" +
      "&pageSize=15";
    HttpRequest httpRequest = HttpRequest.get(url);
    return commonPost(httpRequest,false);
  }


  private String commonPost(HttpRequest request,Boolean reply){

    try {
      request.header("Authorization", TOKEN);
      HttpResponse execute = request.execute();

      int status = execute.getStatus();
      if (!reply && status == 401) {
        TOKEN = login();
        return commonPost(request,true);
      }else if (status == 200){
        return execute.body();
      }else {
        String message = Convert.toStr(com.alibaba.fastjson2.JSONPath.extract(execute.body(), "$.message"));
        BotAssertTool.isActualTrue(true, BotExceptionType.BOT_SERVICE, "请求异常:"+ message);
        return null;
      }
    } catch (HttpException e) {
      log.error("请求异常", e);
      BotAssertTool.isActualTrue(true, BotExceptionType.BOT_SERVICE, "请求异常:未知异常");

      return null;
    }
  }

  public static void main(String[] args){
    String login = login();
    System.out.println(login);
    String searchTicket = searchResourcesOrderInfo("430524200710259098");
    System.out.println(searchTicket);
  }

}
